package com.shop.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shop.dao.impl.ShopDao;
import com.shop.model.Shop;


@WebServlet("/shoppingCar")
public class ShoppingCarServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
    public ShoppingCarServlet() {
        super();
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (request.getParameter("shopName") != null) {	
			//通过product_info跳转
			String shopName = request.getParameter("shopName");
			double price =  Double.parseDouble(request.getParameter("price"));
			Integer number = Integer.parseInt(request.getParameter("number"));
			String account =  (String) request.getSession().getAttribute("account");	
			ShopDao shopDao = new ShopDao();
			//查询该商品是否已在购物车内
			List<Shop> list = shopDao.selShopName(shopName,account);
			//将接受到的数据存入shop中
			Shop shop = new Shop(shopName, price, number,price*number,account);
			System.out.println(shop);
			if (list.size() == 0) {
				//代表购物车中不存在shopName，直接加入购物车
				Integer i = shopDao.insert(shop);
				if (i != null) {
					System.out.println("商品加入购物车成功");				
				} else {
					System.out.println("商品加入购物车失败");
				}		
				
			} else {
				//代表购物车中存在该商品，需更新
				Integer i = shopDao.update(shop);
				if (i != null) {
					System.out.println("更新购物车成功");
				}
			}
			List<Shop> list2 = shopDao.selShoppingCar(account);
			request.setAttribute("list", list2);	
			// 跳转
			request.getRequestDispatcher("shoppingCar.jsp").forward(request, response);	
		}else {
			//点击右上角购物车
			ShopDao shopDao = new ShopDao();			
			String account =  (String) request.getSession().getAttribute("account");
			List<Shop> list2 = shopDao.selShoppingCar(account);
			request.setAttribute("list", list2);
			if (request.getParameter("id") != null) {
				request.getRequestDispatcher("order_info.jsp").forward(request, response);	
			}else {
				// 跳转
				request.getRequestDispatcher("shoppingCar.jsp").forward(request, response);	
			}
		}

		
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
